<?php

namespace app\api\model\kuyou\applet;

use app\api\controller\kuyou\applet\Commons;
use think\Db;
use think\Model;
class Plan extends Model
{

    // 表名
    protected $name = 'kuyou_plan';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';

    /**
     * 获取列表
     * @param array $where
     * @param int $page
     * @param int $limit
     * @return array
     */
    public static function getList($where,$page,$limit){
        $app_page = config('app_page');
        $app_page = $app_page===false?false:true;
        $pageStatus = true;
        if($app_page){
            if($page<0){
                $pageStatus = false;
            }
        }
        if($pageStatus){
            $list = collection(self::where(function ($query) use ($where) {
                $query->where($where);
            })->page($page,$limit)->field('id,purchase_code,purchase_time,delivery_time,workshop_id,number,all_money,examine_id,examine_time,preparation_id,examine_id,operation_id,mrp_status,examine_status')
                ->order(['id'=>'DESC'])->select())->toArray();
        }else{
            $list = collection(self::where(function ($query) use ($where) {
                $query->where($where);
            })->field('id,purchase_code,purchase_time,delivery_time,workshop_id,number,all_money,examine_id,examine_time,preparation_id,examine_id,operation_id,mrp_status,examine_status')
                ->order(['id'=>'DESC'])->select())->toArray();
        }
        $adminList = (new Commons())->adminList();
        foreach ($list as $list_k=>$list_v){
            $list[$list_k]['workshop_id'] = Db::name('kuyou_workshop')->where(['id'=>$list_v['workshop_id']])->value('name');
            $goods_list = Db::name('kuyou_plan_info')->where(['plan_id'=>$list_v['id']])->field('goods_name,number')->select();
            $str = '';
            foreach ($goods_list as $goods_list_k=>$goods_list_v){
                $str .= $goods_list_v['goods_name'].'*'.$goods_list_v['number'].' ';
            }
            $list[$list_k]['goods_info'] = $str;

            $list[$list_k]['purchase_time'] = date('Y-m-d',$list_v['purchase_time']);
            $list[$list_k]['delivery_time'] = date('Y-m-d',$list_v['delivery_time']);
            if(!empty($list_v['examine_time'])){
                $list[$list_k]['examine_time'] = date('Y-m-d',$list_v['examine_time']);
            }
            $list[$list_k]['examine_name'] = isset($adminList[$list_v['examine_id']])?$adminList[$list_v['examine_id']]:'';
            $list[$list_k]['preparation_name'] = isset($adminList[$list_v['examine_id']])?$adminList[$list_v['preparation_id']]:'';
            $list[$list_k]['operation_name'] = isset($adminList[$list_v['examine_id']])?$adminList[$list_v['operation_id']]:'';
        }

        $count = self::where(function ($query) use ($where) {
            $query->where($where);
        })->count();
        return ['list'=>$list,'count'=>$count];
    }

    /**
     * 获取详情
     * @param int $id
     * @return array
     */
    public static function getDetail($id){
        $detail = self::where(function ($query) use ($id) {
            $query->where('id', '=', $id);
        })->field('id,purchase_code,purchase_time,delivery_time,workshop_id,number,all_money,examine_id,examine_time,preparation_id,examine_id,operation_id,mrp_status,remark,examine_status')->find();
        if($detail){
            $detail['workshop_name'] = Db::name('kuyou_workshop')->where(['id'=>$detail['workshop_id']])->value('name');
            $adminList = (new Commons())->adminList();
            $detail['purchase_time'] = date('Y-m-d',$detail['purchase_time']);
            $detail['delivery_time'] = date('Y-m-d',$detail['delivery_time']);
            if(!empty($detail['examine_time'])){
                $detail['examine_time'] = date('Y-m-d',$detail['examine_time']);
            }
            $detail['examine_name'] = isset($adminList[$detail['examine_id']])?$adminList[$detail['examine_id']]:'';
            $detail['preparation_name'] = isset($adminList[$detail['examine_id']])?$adminList[$detail['preparation_id']]:'';
            $detail['operation_name'] = isset($adminList[$detail['examine_id']])?$adminList[$detail['operation_id']]:'';

            $purchase_info = Db::name('kuyou_plan_info')->where(['plan_id'=>$detail['id']])->select();
            $unit = Db::name('kuyou_unit')->column('name','id');
            foreach ($purchase_info as $purchase_info_k=>$purchase_info_v){
                $purchase_info[$purchase_info_k]['goods_image'] = (new Goods())->where(['goods_code'=>$purchase_info_v['goods_code']])->value('goods_image');
                $purchase_info[$purchase_info_k]['unit'] = (new Goods())->getGoodsUnit($purchase_info_v['goods_id']);
                $purchase_info[$purchase_info_k]['unit_name'] = isset($unit[$purchase_info_v['unit_id']])?$unit[$purchase_info_v['unit_id']]:'';
                $purchase_info[$purchase_info_k]['default_unit_name'] = isset($unit[$purchase_info_v['default_unit']])?$unit[$purchase_info_v['default_unit']]:'';
            }
            $detail['info_list'] = $purchase_info;
            return ['status'=>200,'msg'=>$detail];
        }else{
            return ['status'=>500,'msg'=>'未查询到相关信息'];
        }
    }

    /**
     * 添加
     * @param array $detail
     * @return array
     */
    public static function addDetail($detail){
        if(empty($detail)){
            return ['status'=>400,'msg'=>'参数错误'];
        }else{
            $check = (new Commons())->checkParameter($detail,[
                'purchase_code|单据编号' =>'require',
                'purchase_time|单据时间'=>'require',
            ]);
            if(isset($check['status'])){
                return $check;
            }else{
                $status = (new Commons())->checkCode($detail['purchase_code'],31);//验证编号是否合法
                if(!$status){
                    return ['status'=>500,'msg'=>'单据编号格式错误'];
                }
                $row = (new Plan())->where(['purchase_code'=>$detail['purchase_code']])->value('id');
                if($row){
                    return ['status'=>500,'msg'=>'编号已存在'];
                }
                $examine= (new Commons())->getSet('examine','is_checked');
                $detail['info_list'] = (array)json_decode($detail['info_list'], true);
                $number = 0;$all_money = 0;$data=[];
                foreach ($detail['info_list'] as $k=>$v){
                    if(!empty($v['goods_code'])){//有产品编号
                        $number += (float)$v['number'];
                        $all_money += (float)$v['money'];
                        $goods = Db::name('kuyou_goods')->where(['goods_code'=>$v['goods_code']])->field('id,goods_code,goods_name')->find();
                        $data[] = [
                            'goods_id'      =>  $goods['id'],
                            'goods_code'    =>  $goods['goods_code'],
                            'goods_name'    =>  $goods['goods_name'],
                            'unit_id'       =>  (float)$v['goods_unit'],
                            'purchase'      =>  (float)$v['purchase'],
                            'number'        =>  (float)$v['number'],
                            'money'         =>  (float)$v['money'],
                            'default_unit'  =>  (float)$v['default_unit'],
                            'basic_nmber'   =>  (float)$v['basic_nmber'],
                            'createtime'    => time(),
                            'updatetime'    => time(),
                        ];
                    }
                }
                if(empty($data)){
                    return ['status'=>500,'msg'=>'请填写详情数据'];
                }else{
                    $admin_id = (new Commons())->getAdminId();
                    $row = [
                        'purchase_code' =>  $detail['purchase_code'],
                        'purchase_time' =>  !empty($detail['purchase_time'])?strtotime($detail['purchase_time']):0,
                        'delivery_time' =>  !empty($detail['delivery_time'])?strtotime($detail['delivery_time']):0,
                        'workshop_id'   =>  $detail['workshop_id'],
                        'remark'        =>  $detail['remark'],
                        'preparation_id'=>  $admin_id,
                        'operation_id'  =>  $admin_id,
                        'createtime'    =>  time(),
                        'updatetime'    =>  time(),
                    ];
                }
                $res = false;
                Db::startTrans();
                try {
                    $res = (new Plan())->insertGetId($row);
                    foreach ($data as $data_k=>$data_v){
                        $data[$data_k]['plan_id'] = $res;
                    }
                    Db::name('kuyou_plan_info')->insertAll($data);
                    $count = Db::name('kuyou_plan_info')->where(['plan_id'=>$res])->field('sum(number) as number,sum(money) as money')->select();
                    if(isset($count[0]['number'])){
                        (new Plan())->where(['id'=>$res])->update(['number'=>$count[0]['number'],'all_money'=>$count[0]['money']]);
                    }
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    $res = false;$msg = $e->getMessage();
                }
                if($res){
                    if($examine!=1){
                        try {
                            $exa = self::examine($res);
                        } catch (\Exception $e) {
                        }
                        if(!isset($exa['status']) || (isset($exa['status']) && $exa['status']!=1)){
                            try {
                                self::delDetail($res);
                            } catch (\Exception $e) {
                            }
                            return ['status'=>500,'msg'=>$exa['msg']];
                        }
                    }
                    return ['status'=>200,'msg'=>$res];
                }else{
                    return ['status'=>500,'msg'=>(isset($msg)?$msg:'添加失败')];
                }
            }
        }
    }

    /**
     * 更新
     * @param array $detail
     * @return array
     */
    public static function editDetail($detail){
        if(empty($detail)){
            return ['status'=>400,'msg'=>'参数错误'];
        }else{
            $check = (new Commons())->checkParameter($detail,[
                'id|ID'=>'require|number',
                'purchase_code|单据编号' =>'require',
                'purchase_time|单据时间'=>'require',
            ]);
            if(isset($check['status'])){
                return $check;
            }else{
                $status = (new Commons())->checkCode($detail['purchase_code'],31);//验证编号是否合法
                if(!$status){
                    return ['status'=>500,'msg'=>'单据编号格式错误'];
                }
                $row = (new Plan())->where(['purchase_code'=>$detail['purchase_code'],'id'=>['<>',$detail['id']]])->value('id');
                if($row){
                    return ['status'=>500,'msg'=>'编号已存在'];
                }
                $examine= (new Commons())->getSet('examine','is_checked');
                $id = $detail['id'];unset($detail['id']);

                $model = new Plan();
                $row = $model->where(['id'=>$id])->find();
                if(empty($row)){
                    return ['status'=>500,'msg'=>'修改的单据不存在'];
                }
                if($examine==1 && $row['examine_status']==1){
                    return ['status'=>500,'msg'=>'不可修改已审核的单据'];
                }

                $detail['info_list'] = (array)json_decode($detail['info_list'], true);
                $number = 0;$all_money = 0;$data=[];
                foreach ($detail['info_list'] as $k=>$v){
                    if(!empty($v['goods_code'])){//有产品编号
                        $number += (float)$v['number'];
                        $all_money += (float)$v['money'];
                        $goods = Db::name('kuyou_goods')->where(['goods_code'=>$v['goods_code']])->field('id,goods_code,goods_name')->find();
                        $data[] = [
                            'goods_id'      =>  $goods['id'],
                            'goods_code'    =>  $goods['goods_code'],
                            'goods_name'    =>  $goods['goods_name'],
                            'unit_id'       =>  (float)$v['goods_unit'],
                            'purchase'      =>  (float)$v['purchase'],
                            'number'        =>  (float)$v['number'],
                            'money'         =>  (float)$v['money'],
                            'default_unit'  =>  (float)$v['default_unit'],
                            'basic_nmber'   =>  (float)$v['basic_nmber'],
                            'createtime'    => time(),
                            'updatetime'    => time(),
                        ];
                    }
                }
                if(empty($data)){
                    return ['status'=>500,'msg'=>'请填写详情数据'];
                }else{
                    $admin_id = (new Commons())->getAdminId();
                    $row = [
                        'purchase_code' =>  $detail['purchase_code'],
                        'purchase_time' =>  !empty($detail['purchase_time'])?strtotime($detail['purchase_time']):0,
                        'delivery_time' =>  !empty($detail['delivery_time'])?strtotime($detail['delivery_time']):0,
                        'workshop_id'   =>  $detail['workshop_id'],
                        'remark'        =>  $detail['remark'],
                        'operation_id'  =>  $admin_id,
                        'updatetime'    =>  time(),
                    ];
                }

                $res = false;
                Db::startTrans();
                try {
                    //关闭审核功能需先反审核一次已审核数据
                    $exa['status']=1;
                    if($examine!=1 && $row['examine_status']==1){
                        $exa = self::examinef($id);
                    }
                    if(isset($exa['status']) && $exa['status']==1){
                        unset($detail['info_list']);
                        $res = (new Plan())->where(['id'=>$id])->update($row);

                        foreach ($data as $data_k=>$data_v){
                            $data[$data_k]['plan_id'] = $id;
                        }
                        Db::name('kuyou_plan_info')->where(['plan_id'=>$id])->delete();
                        Db::name('kuyou_plan_info')->insertAll($data);
                        $count = Db::name('kuyou_plan_info')->where(['plan_id'=>$id])->field('sum(number) as number,sum(money) as money')->select();
                        if(isset($count[0]['number'])){
                            Db::name('kuyou_plan')->where(['id'=>$id])->update(['number'=>$count[0]['number'],'all_money'=>$count[0]['money']]);
                        }
                    }
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    $res = false;$msg = $e->getMessage();
                }

                if($res){
                    if($examine!=1){
                        try {
                            $exa = self::examine($id);
                        } catch (\Exception $e) {
                        }
                        if(!isset($exa['status']) || (isset($exa['status']) && $exa['status']!=1)){
                            return ['status'=>500,'msg'=>$exa['msg']];
                        }
                    }
                    return ['status'=>200,'msg'=>'更新成功'];
                }else{
                    return ['status'=>500,'msg'=>(isset($msg)?$msg:'更新失败')];
                }
            }
        }
    }

    /**
     * 删除
     * @param int $id
     * @return array
     */
    public static function delDetail($id){
        if(empty($id)){
            return ['status'=>400,'msg'=>'参数错误'];
        }else{
            $list = (new Plan())->where(['id'=>['in',$id]])->select();
            $examine= Db::name('kuyou_sets')->where(['name'=>'examine'])->value('is_checked');
            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $exa['status']=1;
                    if($v['examine_status']==1 && $examine==1){
                        exception('不能删除已审核的数据');
                    }elseif ($v['examine_status']==1 && $examine!=1){
                        try {
                            $exa = self::examine($v['id']);
                        } catch (\Exception $e) {
                        }
                    }
                    if(isset($exa['status']) && $exa['status']==1){
                        $count += $v->delete();
                        Db::name('kuyou_plan_info')->where(['plan_id'=>$v['id']])->delete();
                    }
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $count = 0;
            }

            if($count){
                return ['status'=>200,'msg'=>$count];
            }else{
                return ['status'=>500,'msg'=>'删除失败'];
            }
        }
    }

    /**
     * 审核
     * @param array $purchase_code
     * @return array
     */
    public static function examine($ids = null){
        if(empty($ids)){
            return ['status'=>400,'msg'=>'请选择要操作的数据'];
        }
        $adminId = (new Commons())->getAdminId();
        $model = new Plan();
        $list = $model->where(['id'=>['in',$ids],'examine_status'=>'0'])->select();
        if(empty($list)){
            return ['status'=>500,'msg'=>'请选择需要审核的数据'];
        }

        Db::startTrans();
        try {
            $result = $model->where(['id'=>['in',$ids],'examine_status'=>'0'])
                ->update(['examine_status'=>1,'examine_id'=>$adminId,'examine_time'=>time(),'operation_id'=>$adminId]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return ['status'=>500,'msg'=>$e->getMessage()];
        }
        if(isset($result) && $result !== false){
            return ['status'=>1,'msg'=>sizeof($list)];
        }else{
            return ['status'=>500,'msg'=>'审核失败'];
        }
    }

    /**
     * 反审核
     * @param array $purchase_code
     * @return array
     */
    public static function examinef($ids = null){
        if(empty($ids)){
            return ['status'=>400,'msg'=>'请选择要操作的数据'];
        }
        $adminId = (new Commons())->getAdminId();
        $model = new Plan();
        $list = $model->where(['id'=>['in',$ids],'examine_status'=>'1'])->select();
        if(empty($list)){
            return ['status'=>500,'msg'=>'请选择需要反审核的数据'];
        }
        foreach ($list as $list_k=>$list_v){
            $order = Db::name('kuyou_production')->where(['plan_code'=>$list_v['purchase_code']])->column('id');
            if(!empty($order)){
                return ['status'=>500,'msg'=>'不能反审核已生成生产单的数据'];
            }
            $order = Db::name('kuyou_outsourcing')->where(['plan_code'=>$list_v['purchase_code']])->column('id');
            if(!empty($order)){
                return ['status'=>500,'msg'=>'不能反审核已生成委外加工单的数据'];
            }
        }
        Db::startTrans();
        try {
            $result = $model->where(['id'=>['in',$ids],'examine_status'=>'1'])
                ->update(['examine_status'=>0,'examine_id'=>0,'examine_time'=>0,'operation_id'=>$adminId]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return ['status'=>500,'msg'=>$e->getMessage()];
        }
        if(isset($result) && $result !== false){
            return ['status'=>1,'msg'=>sizeof($list)];
        }else{
            return ['status'=>500,'msg'=>'反审核失败'];
        }
    }

}
